package com.wzh.project.redis.main;

import java.io.Serializable;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.wzh.project.common.Constants;
import com.wzh.project.redis.bean.Message;
import com.wzh.project.redis.consumer.ConsumerThread;
import com.wzh.project.redis.utils.JedisUtils;
import com.wzh.project.redis.utils.ReplyQueueUtil;

public class TestMain {
	private static final Logger logger = LogManager.getLogger(TestMain.class);
	private static ExecutorService executorService =Executors.newFixedThreadPool(5);
	private static String queueName="queue";//默认发送，监听的队列名
	private static String serverInfo="redis";//默认的服务器信息,该key对应一个配置文件
	public static void main(String[] args) throws Exception {
		//===测试队列
//		startConsumer();
//		startProducer();
		//测试缓存
		String key=UUID.randomUUID().toString();
		Message message=new Message();
		message.setName("汪振海");
		setRedisCache(key, message);
		getRedisCacheValue(key);
	}
	/**
	 * 启动消费者进程
	 */
	public static void startConsumer() {
		logger.debug("启动消费者线程监听");
		ConsumerThread consumerThread=new ConsumerThread();
		consumerThread.setQueueName(queueName);//设定监听的队列名
		consumerThread.setRedisName(serverInfo);//设定加载的配置文件
		executorService.execute(consumerThread);
	}
	/**
	 * 启动生产者线程
	 * @throws Exception 
	 */
	public static void startProducer() throws Exception {
		logger.debug("启动生产者线程");
		String replyName=ReplyQueueUtil.getReplyQueue();//产生回复队列名
		//========================//
		logger.debug("启动生产者的回复线程监听,若发送的消息不需要回复则可不启动");
		ConsumerThread consumerThread=new ConsumerThread();
		consumerThread.setQueueName(replyName);//设定监听的队列名
		consumerThread.setRedisName(serverInfo);//设定加载的配置文件
		executorService.execute(consumerThread);
		//=======================//
		//发送消息
		Message message=new Message();
		message.setName("汪振海");
		String uuid=UUID.randomUUID().toString();
		boolean isReply=true;
		String serviceName="DealService";
		Message result=(Message) JedisUtils.sendObj(serverInfo, queueName, serviceName, message,uuid, Constants.W2N, isReply);
		if(isReply) {
			logger.debug("回复的消息内容为"+result.getName());
		}
		
	}
	
	/**
	 * 向redis缓存中存放数据
	 * @throws Exception 
	 */
	public static void setRedisCache(String key,Serializable value) throws Exception {
		JedisUtils.setCacheData(serverInfo, key, value, false, "ex", 100);
	}
	/**
	 * 从缓存中获取数据
	 * @param key
	 * @throws Exception
	 */
	public static void getRedisCacheValue(String key) throws Exception {
		Message mess=(Message) JedisUtils.getCacheData(serverInfo, key);
		logger.debug(mess.getName());
	}
	

}
